package com.hmall.order.job;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hmall.client.ItemClient;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * TODO
 *
 * @Author wangxinyi
 * @Date 2024/11/16 10:13
 */
@Component
public class CancelOrderTask {


    @Autowired
    private ItemClient itemClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Scheduled(cron = "0 0/1 * * * ?")
    //每隔一分钟执行一次
    public void cancelOrderTask() {
        //查询status=1(未支付)，并且下单超过30分钟的 sql 两个时间差
        List<Order> orderList = orderMapper.selectOrder();
        for (Order order : orderList) {
            //根据orderId从订单详情表种查询商品id和商品数量
            OrderDetail orderDetail = orderDetailMapper.selectByOrderId(order.getId());
            Integer num = orderDetail.getNum();
            Long itemId = orderDetail.getItemId();
            //调用item-service，根据商品id、商品数量恢复库存
            itemClient.runNum(itemId,num);
            //根据orderId修改订单status为5 （交易取消，订单关闭）
            LambdaUpdateWrapper<Order> UpdateWrapper = new LambdaUpdateWrapper<>();
            UpdateWrapper.set(Order::getStatus,5).eq(Order::getId,order.getId());
            orderMapper.update(null,UpdateWrapper);
        }
    }
}
